package pro.ticktock.base.tree.impl;

import pro.ticktock.base.tree.api.TreeNode;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

/*
 * Author: lambo
 * Date: 2018-09-30
 */
public class TreeNodeImpl<NV>
        extends AbstractTreeNode<TreeNode<NV>, NV>
        implements TreeNode<NV> {

  public List<TreeNode<NV>> childList;

  public TreeNodeImpl() {
    this(null);
  }

  public TreeNodeImpl(NV value) {
    childList = new LinkedList<>();
    setValue(value);
  }

  @Override
  public Collection<TreeNode<NV>> getChildList() {
    return childList;
  }

  @Override
  public void addChild(TreeNode<NV> child) {
    childList.add(child);
    child.setParent(this);
  }

  @Override
  public void addChild(int idx, TreeNode<NV> child) {
    childList.add(idx, child);
  }

  @Override
  public boolean removeChild(TreeNode<NV> child) {
    boolean removed = childList.remove(child);
    if (removed) child.setParent(null);
    return removed;
  }

  @Override
  public TreeNode<NV> removeChildAt(int idx) {
    return childList.remove(idx);
  }

  @Override
  public int getChildCount() {
    return childList.size();
  }

  @Override
  public TreeNode<NV> childAt(int index) {
    return childList.get(index);
  }

  @Override
  public int indexOf(TreeNode<NV> child) {
    return childList.indexOf(child);
  }

  public void clearChild() {
    childList.stream().forEach(c -> c.setParent(null));
    childList.clear();
  }
}
